import { store } from "./store";
import { translate } from '@/i18n'

export function formatI18nTemplate(template) {
	if (!template) return "";

	const pattern = /\{\{\s*.+\s*\}\}/g;
	const matches = template.match(pattern);
	// console.debug("[i18n] matches: ", matches);

	if (!matches) return template;

	let temp = template;

	matches.forEach(item => {
		const key = item.substring(2, item.length - 2).trim();
		const value = translate(key);

		temp = temp.replaceAll(item, value);
	});

	return temp;
}

export function changeTitle(title, autoI18n = true) {
	if (!title) return;

	store.changeTitle(title);


	let newTitle = title;

	if (autoI18n) {
		newTitle = formatI18nTemplate(title);
	}

	document.title = `${newTitle} - TOJ`;
};


